package com.simplefan.system.client.applet.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class ServletConnection {
  public static String Post(String urlString, String content) {
    try {
    URL url =new URL(urlString);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    
//    conn.setConnectTimeout();
//    conn.setReadTimeout();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    
    OutputStream output = conn.getOutputStream();
    
    output.write(content.getBytes());
    output.flush();
    output.close();
    
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn
            .getInputStream()));
    String line;
    StringBuffer buffer = new StringBuffer();
    
    while ((line = reader.readLine()) != null) {
        buffer.append(line);
    }
    
    String value = buffer.toString();

    //value = URLDecoder.decode(value, IMSCParameter.getINTERNAL_CHARSET());
    return value;
    }
    catch (Exception exception) {
      throw new RuntimeException(exception);
    }
  }

  public static String Send(String url, String parameters) {
    String queryString = url + "?" + parameters;
    System.out.println("request:" + queryString);
    try {
      URL servletURL = new URL(queryString);
      URLConnection connect = servletURL.openConnection();
      connect.setDefaultUseCaches(false);
      connect.setUseCaches(false);
      connect.setDoInput(true);
      connect.setDoOutput(false);
      connect.connect();
      DataInputStream in = new DataInputStream(connect.getInputStream());
      StringBuffer message = new StringBuffer();
      String line = in.readLine();
      while(line != null) {
        message.append(line);
        line = in.readLine();

      }
      return message.toString();
    }
    catch(Exception exception) {
      exception.printStackTrace();
      return null;
    }
  }

  public static void main(String[] args) {
    System.out.println(Send("http://127.0.0.1:8080/ngrm/applet/imageUrl.imageUrl.d", "id=102&metaClass=com.simplefan.equipment.Port"));
  }
}
